import { useEffect, useRef, useState } from "react"
import PropTypes from "prop-types"
import CommonForm from "./CommonForm"
import CommonModal from "./CommonModal"

const CommonModalForm = ({
  disabled,
  title,
  visible,
  onCancel,
  onSubmit,
  initValues,
  formItems
}) => {

  const [sending, setSending] = useState(false)

  const formRef = useRef(null)

  const triggerSubmit = () => {
    formRef.current.submit()
  }

  const handleSubmit = (values) => {
    if (!sending) {
      setSending(true)
      onSubmit && onSubmit(values, () => {
        setSending(false)
      })
    }
  }

  const handleAfterClose = () => {
    formRef.current.resetFields()
    setTimeout(() => {
      setSending(false)
    }, 500)
  }

  useEffect(() => {
    if (visible) {
      formRef.current.setFieldsValue(initValues)
    }
  }, [visible])

  const modalProps = {
    visible,
    title,
    okText: "提交",
    okButtonProps: {
      loading: sending
    },
    afterClose: handleAfterClose,
    onCancel: onCancel,
    onOk: triggerSubmit
  }

  if (disabled) {
    modalProps.footer = null
  }

  return <CommonModal
    {...modalProps}
  >
    <div style={{ paddingTop: 2 }}>
      <CommonForm
        ref={formRef}
        formItems={formItems}
        onSubmit={handleSubmit}
        disabled={disabled}
      ></CommonForm>
    </div>
  </CommonModal>

}

CommonModalForm.propTypes = {
  disabled: PropTypes.bool,
  title: PropTypes.string,
  visible: PropTypes.bool,
  onCancel: PropTypes.func,
  onSubmit: PropTypes.func,
  initValues: PropTypes.object,
  formItems: PropTypes.array
}

export default CommonModalForm